<?php

error_reporting(E_ALL|E_STRICT);

def test($str) = {
	static $i = 0;
	++$i;
	puts "$i) $str\n";
}

def h1($s) = puts "\n### $s ###\n";
def h2($s) = puts "## $s ##\n";
def flat($a) = puts(implode(',', $a)) . "\n";

def defSingleLine($x) = <- $x * $x;

def defMultipleLines($x) = {
	$x *= $x;
	<- $x;
}

def defNoArgsSingleLine = <- 'No args';

def defNoArgsMultipleLines = {
	$x = 'No args' . ' multiple lines.';
	<- $x;
}

def lambdaSingleLine() = {
	<-preg_replace_callback('~-([a-z])~',def ($_) = <-strtoupper($_[1]);, 'hello-world');
}

def lambdaMultipleLine() = {
	<-preg_replace_callback('~-([a-z])~',def($_) = {
			$_[1] = ' ' . $_[1];
			<-strtoupper($_[1]);
		}	
		, 'hello-world');
}

def lambdaSingleLineNoArgs() = {
	<-preg_replace_callback('~-([a-z])~',def = <- ' my w';, 'hello-world');
}

def lambdaMultipleLineNoArgs() = {
	<-preg_replace_callback('~-([a-z])~',def = {
			<- ' cool w';
		}	
		, 'hello-world');
}

def arraySyntax() = {
	$a = [4: 'New', 7: ['woot': 'Coolness']];
	<- $a[7]['woot'];
}

def castShortForm() = {
	$a = (i)(d)(a)(o)(bi)(b)(s) '1';
	<- $a;
}

def square(&$a) = array_walk($a, def(&$v,$k)=$v*=$v;);
def less_than_ten(&$a) = <-array_filter($a, def($v)=<-($v<10););

// Running test functions.
h1('Testing functions');
test(defSingleLine(4)); //1
test(defMultipleLines(9)); //2
test(defNoArgsSingleLine()); //3
test(defNoArgsMultipleLines()); //4
test(lambdaSingleLine()); //5
test(lambdaMultipleLine()); //6
test(lambdaSingleLineNoArgs()); //7
test(lambdaMultipleLineNoArgs()); //8
test(arraySyntax()); //9
test(castShortForm()); //10

$a = array(1, 2, 3, 4, 5);
h1('Testing functional functions');
h2('square');
square($a);
flat($a);
h2('less_than_ten');
flat(less_than_ten($a));